import React, { useRef } from 'react'
// 引入connect用于连接UI组件与redux
import { connect } from 'react-redux'
// 引入action
import { createIncrementAction, createDecrementAction, createIncrementAsyncAction } from '../../redux/actions/count'

function Count(props) {
  // console.log(props);

  const selectNumberRef = useRef()

  /**
   * 加
   */
  const increment = () => {
    const { value } = selectNumberRef.current
    props.jia(value * 1)
  }

  /**
   * 减
   */
  const decrement = () => {
    const { value } = selectNumberRef.current
    props.jian(value * 1)
  }

  /**
   * 如果为奇数，则加
   */
  const incrementIfOdd = () => {
    const { value } = selectNumberRef.current
    if (props.count % 2 !== 0) {
      props.jia(value * 1)
    }
  }

  /**
   * 异步延迟加
   */
  const incrementIfAsync = () => {
    const { value } = selectNumberRef.current
    props.jiaAsync(value * 1, 500)
  }

  return (
    <div>
      <h1>我是Count组件，下方组件总人数为{props.persons.length}</h1>
      <h2>当前求和为：{props.count}</h2>
      <select ref={selectNumberRef}>
        <option value='1'>1</option>
        <option value='2'>2</option>
        <option value='3'>3</option>
      </select>
      <button onClick={increment}>+</button>
      <button onClick={decrement}>-</button>
      <button onClick={incrementIfOdd}>当前求和为奇数再加</button>
      <button onClick={incrementIfAsync}>异步加</button>
    </div>
  )
}

export default connect(
  (state) => ({ count: state.count, persons: state.persons }),
  // react-redux提供的简写方式用对象{}，可以不用函数形式，自动加工到dispatch中
  {
    jia: createIncrementAction,
    jian: createDecrementAction,
    jiaAsync: createIncrementAsyncAction
  }
)(Count)
